<?php
/*
 * FileName appModel.php
 * Date		2012-7-25
 * Author	jime
 * Mail 	me@joyphper.net
 * QQ		97142822
 * Copyright (C) 2012 joyphper.net
 */
if (! defined ( 'App_PATH' ))exit ( 'request error' );
import("core/classes/Mysql.class.php");
class AppBaseService{
	private $conn;//数据库连接

	public function AppBaseService(){
		//数据化mysql连接
		$this->conn=new Mysql(C("db"));
		$this->conn->transaction();
	}
	public function __destruct(){     //应用析构函数自动释放连接资源
		if(in_array(false,$this->conn->queryRes)){//监听所有的sql执行状态，如果发现错误立刻回滚
			$this->conn->rollback();
		}else{
			$this->conn->commit();
		}
	}

	public function conn(){
		return $this->conn;
	}
	/**
	 * 执行SQL语句，相等于执行新增，修改，删除等操作。
	 *
	 * @param sql 字符串，需要执行的SQL语句
	 */
	public function runSql($sql)
	{
		return $this->conn->query($sql);
	}
	/**
	 * 通过sql查询
	 */
	public function findBySql($sql){
		if($row=$this->conn->getArray($sql)){
			return $row;
		}else{
			return false;
		}
	}
	public function pagerBySql($sql,$curPage,$pageSize){

		//总的记录数
		$_arr = $this->conn->getArray("select count(*) as N from (".$sql.") as a");
		$totalCount =$_arr ?$_arr[0]["N"]:0;

		//总的分页数
		$totalPage =ceil($totalCount/$pageSize);

		//取有效的总页数
		if($totalPage<=0 ) $totalPage = 1;

		//取有效的当前页
		if(!is_numeric($curPage)) $curPage =1;
		$curPage = $curPage > $totalPage ? $totalPage:$curPage;

		$querySql=$sql." limit ".(($curPage-1)*$pageSize).",".$pageSize;
		$row = $this->conn->getArray($querySql);
		if(!$row)$row=array();
		$pager = array(
			"count" 	=> $totalCount,                                 // 总记录数
			"size"   	=> $pageSize,                              		// 分页大小
			"total"  	=> $totalPage,                                  // 总页数
			"first"  	=> 1,                                           // 第一页
			"prev"   	=> ( ( $curPage <=1	 ) ? 1 : ($curPage- 1) ),  	// 上一页
			"next"   	=> ( ( $curPage >= $totalPage ) ? $totalPage : ($curPage + 1)),     // 下一页
			"last"   	=> $totalPage,                                // 最后一页
			"current"	=> $curPage,                                  // 当前页
			"numbers"   => array(),                                   // 页码数字
			"records" 	=> $row
		);
		if($totalPage>11){
			if($curPage<=6){
				$forStart=1;
				$forEnd=11;
			}elseif ($curPage + 5 > $totalPage){
				$forStart=$totalPage-10;
				$forEnd=$totalPage;
			}else{
				$forStart=$curPage-5;
				$forEnd=$curPage+5;
			}
		}else{
			$forStart=1;
			$forEnd=$totalPage;
		}
		for($i=$forStart; $i <= $forEnd; $i++)$pager['numbers'][] = $i;
		return $pager;
	}
	/**
	 * 添加一件记录
	 */
	public function insert($tblName,$fields){
		if(!is_array($fields) || empty($tblName))return FALSE;
		$row = $this->__prepera_format($tblName,$fields);
		if(empty($row))return false;
		foreach($row as $key => $value){
			$cols[] = $key;
			$vals[] = $this->conn->__val_escape($value);
		}
		$col = join(',', $cols);
		$val = join(',', $vals);

		$sql = "INSERT INTO {$tblName} ({$col}) VALUES ({$val})";
		if( false != $this->conn->query($sql) ){ // 获取当前新增的ID
			if( $newinserid = $this->conn->getInsertId() )
				return $newinserid;
			else
				return true;
		}
		return false;
	}
	/**
	 * 更新操作
	 */
	public function update($tblName,$fields,$conditions){
		if(empty($tblName) || !is_array($fields)) return false;
		$row = $this->__prepera_format($tblName,$fields);
		if(empty($row))return false;

		//构造更新条件
		if(is_array($conditions)){
			$join = array();
			foreach( $conditions as $key => $condition ){
				$condition = $this->conn->__val_escape($condition);
				$join[] = "{$key} = {$condition}";
			}
			$where = "WHERE ".join(" AND ",$join);
		}else{
			if(null != $conditions)$where = "WHERE ".$conditions;
		}
		//构造更新字段

		foreach($row as $key => $value){
			$value = $this->conn->__val_escape($value);
			$vals[] = "{$key} = {$value}";
		}
		$values = join(", ",$vals);

		//形成最终的sql
		$sql = "UPDATE {$tblName} SET {$values} {$where}";

		return $this->conn->query($sql);
	}
	/**
	 * 按条件删除记录
	 *
	 * @param conditions 数组形式，查找条件，此参数的格式用法与find/findAll的查找条件参数是相同的。
	 */
	public function delete($tblName,$conditions)
	{
		if(empty($tblName)) return false;
		$where = "";
		if(is_array($conditions)){
			$join = array();
			foreach( $conditions as $key => $condition ){
				$condition = $this->conn->__val_escape($condition);
				$join[] = "{$key} = {$condition}";
			}
			$where = "WHERE ( ".join(" AND ",$join). ")";
		}else{
			if(null != $conditions)$where = "WHERE ( ".$conditions. ")";
		}
		$sql = "DELETE FROM {$tblName} {$where}";
		return $this->conn->query($sql);
	}
	/**
	 * 返回执行的SQL语句供分析
	 */
	public function dumpSql()
	{
		print_r( $this->conn->arrSql );
	}
	/**
	 * 返回上次执行update,create,delete,exec的影响行数
	 */
	public function affectedRows()
	{
		return $this->conn->affectedRows();
	}
	/**
	 * 按表字段调整适合的字段
	 * @param rows    输入的表字段
	 */
	private function __prepera_format($tblName,$rows)
	{
		$columns = $this->conn->getTable($tblName);
		$newcol = array();
		foreach( $columns as $col ){
			$newcol[$col['Field']] = $col['Field'];
		}
		return array_intersect_key($rows,$newcol);
	}
}
?>
